package com.android.lovely.room.chat

import com.android.lovely.room.chat.database.CacheMessage
import com.android.lovely.room.chat.database.ChatDatabase
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.coroutine.applicationScope

object ChatHelper {


    suspend fun getMessages(botId: Int, messageId: Int, loadSize: Int): List<CacheMessage> {
        return ChatDatabase.getInstance().getChatDao().getMessages(botId, messageId, loadSize)
    }

    fun insertMessages(messages: List<CacheMessage>) {
        applicationScope.launchSafety {
            ChatDatabase.getInstance().getChatDao().insertMessages(messages)
        }
    }

    fun insertMessage(message: CacheMessage) {
        applicationScope.launchSafety {
            ChatDatabase.getInstance().getChatDao().insertMessage(message)
        }
    }

    fun updateMessage(messageId: Int, message: CacheMessage.() -> Unit) {
        applicationScope.launchSafety {
            val locale = ChatDatabase.getInstance().getChatDao().getMessage(messageId)
            locale?.apply(message)
            if (locale != null) {
                ChatDatabase.getInstance().getChatDao().insertMessage(locale)
            }
        }
    }

    fun deleteSendMessage(messageId: Int) {
        applicationScope.launchSafety {
            ChatDatabase.getInstance().getChatDao().deleteSendMessage(messageId)
        }
    }

    fun deleteReceivedMessage(messageId: Int) {
        applicationScope.launchSafety {
            ChatDatabase.getInstance().getChatDao().deleteReceivedMessage(messageId)
        }
    }

    fun clearMessage(botId: Int) {
        applicationScope.launchSafety {
            ChatDatabase.getInstance().getChatDao().deleteMessages(botId)
        }
    }
}